<template>
  <div id="Home">
    <!--<van-notice-bar-->
    <!--left-icon="volume-o"-->
    <!--background="#2cafaf"-->
    <!--color="#fff"-->
    <!--text="系统通知：巴中-西昌1月2日还有余票，请查询后往下滑"-->
    <!--/>-->
    <!--轮播图-->
    <van-swipe class="my-swipe" :autoplay="3000" indicator-color="#0fa1a0">
      <van-swipe-item v-for="item in banner" :key="item.link_url">
        <img v-lazy="item.path" @click="imgBtn(item.link_url)" />
        <!--<img :src="item.path"/>-->
      </van-swipe-item>
    </van-swipe>
    <!--搜索框-->
    <div class="searchF flex aCenter column">
      <div class="search">
        <div class="changeBooking flex aCenter between" v-if="isExchange">
          <div
            @click="goToIndexAnchorS"
            class="Select_active"
            :class="{ fontColor: isDeparture }"
          >
            {{ Departure }}
          </div>
          <span @click="exchange"
            ><img src="@/assets/img/changeBooking.png"
          /></span>
          <div
            @click="goToIndexAnchorE"
            class="Select_active flex jEnd"
            :class="{ fontColor: isArrive }"
          >
            {{ arrive }}
          </div>
        </div>
        <div class="changeBooking flex aCenter between" v-if="!isExchange">
          <div
            @click="goToIndexAnchorS"
            class="Select_active"
            :class="{ fontColor: isArrive }"
          >
            {{ Departure }}
          </div>
          <span @click="exchange"
            ><img src="@/assets/img/changeBooking.png"
          /></span>
          <div
            @click="goToIndexAnchorE"
            class="Select_active flex jEnd"
            :class="{ fontColor: isDeparture }"
          >
            {{ arrive }}
          </div>
        </div>
        <div style="width: 100%" class="flex jCenter">
          <div class="line"></div>
        </div>
        <van-cell is-link to="/Calendar">
          <template #title>
            <div class="Select_time">{{ dateSearch }}</div>
          </template>
        </van-cell>
        <div class="btn">
          <van-button
            @click="toSearchResult"
            type="primary"
            color="#0fa1a0"
            round
            block
            >查询</van-button
          >
        </div>
      </div>
    </div>
    <div class="titleF flex aCenter">
      <div class="lineH"></div>
      <div class="title">热门推荐</div>
    </div>
    <!--列表-->

    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <div v-for="(item, index) in circuit" :key="index" >
          <template v-if="item.s_ticket != 0">
            <div
              class="listF flex aCenter column"
              @click="toSubmit(item.id, item.pt_id)"
            >
              <div class="list flex between">
                <div class="marL">
                  <div class="mar">{{item.citysname}}</div>
                  <!-- <div class="mar">{{ item.s_address }}</div> -->
                  <div class="mar listFont">{{ item.s_address }}</div>
                  <!-- <div class="mar listFont">{{ item.sitesname }}</div> -->
                </div>
                <div class="ban flex column jCenter aCenter">
                  <div class="mar">{{ item.hour }}</div>
                  <div>
                    <div class="arrow"></div>
                    <div class="rotate"></div>
                  </div>
                  <div class="mar">{{ item.day | dateChange }}</div>
                </div>
                <div class="abmarL">
                  <!-- <div class="mar marL">{{ item.e_address }}</div> -->
                  <div class="mar marL">{{item.cityename}}</div>
                  <div class="mar marL listFont">{{ item.e_address }}</div>
                </div>
                <div class="marR flex column aEnd">
                  <div class="money">￥{{ item.ticket_price }}</div>
                  <div class="mar Remaining">余票{{ item.s_ticket }}张</div>
                </div>
              </div>
            </div>
          </template>
          <template v-if="item.s_ticket == 0">
            <div class="listF flex aCenter column" @click="noneTicket">
              <div class="list flex between">
                <div class="marL">
                  <!-- <div class="mar grey">{{ item.s_address }}</div> -->
                  <div class="mar grey">{{item.citysname}}</div>
                  <div class="mar listFont grey">{{ item.s_address }}</div>
                </div>
                <div class="ban flex column jCenter aCenter">
                  <div class="mar grey">{{ item.hour }}</div>
                  <div>
                    <div class="arrow"></div>
                    <div class="rotate"></div>
                  </div>
                  <div class="mar grey">{{ item.day | dateChange }}</div>
                </div>
                <div class="abmarL">
                  <!-- <div class="mar marL grey">{{ item.e_address }}</div> -->
                  <div class="mar marL grey">{{item.cityename}}</div>
                  <div class="mar marL listFont grey">{{ item.e_address }}</div>
                  <!-- <div class="mar marL listFont grey">{{ item.siteename }}</div> -->
                </div>
                <div class="marR flex column aEnd">
                  <div class="money grey">￥{{ item.ticket_price }}</div>
                  <div class="mar Remaining">余票{{ item.s_ticket }}张</div>
                </div>
              </div>
            </div>
          </template>
        </div>
      </van-list>
    </van-pull-refresh>
    <FooterBar />
    <Loading :isLoading="isLoading" />
  </div>
</template>

<script>
import Loading from "components/Loading.vue";
import FooterBar from "components/FooterBar.vue";
import { code, circuit, banner, bind } from "@/api/home";
export default {
  data() {
    return {
      Departure: "出发站",
      arrive: "到达站",
      isDeparture: true,
      isArrive: true,
      isExchange: true,
      circuit: [],
      banner: [],
      isLoading: false,
      dateSearch: "",
      loading: false,
      finished: false,
      refreshing: false,
      page: 0,
      isToken: false,
    };
  },
  components: {
    FooterBar,
    Loading,
  },
  methods: {
    // 执行绑粉
    executeBind() {
      const data = {
        token: this.$store.state.token,
        uid: localStorage.getItem('uid')
      };
      bind(data)
        .then((res) => {
          if (res.data.flag) {
          } else {
            this.$toast(res.data.msg);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    noneTicket() {
      this.$toast("暂无余票");
    },
    imgBtn(link_url) {
      if (link_url) {
        location.href = "http://" + link_url;
      }
    },
    getUrlCode() {
      // 截取url中的code方法
      let url = location.search;
      this.winUrl = url;
      let theRequest = new Object();
      if (url.indexOf("?") != -1) {
        let str = url.substr(1);
        let strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
          theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
        }
      }
      return theRequest;
    },
    toSubmit(id, pt_id) {
      this.$router.push({ path: "/orderSubmit", query: { id, pt_id } });
    },
    onRefresh() {
      this.finished = false;
      this.page = 0;
      this.circuit = [];
      this.loading = true;
      this.onLoad();
    },
    onLoad() {
      if (this.isToken) {
        this.loading = true;
        if (this.refreshing) {
          this.circuit = [];
          this.refreshing = false;
        }
        this.page++;
        let data = {
          token: this.$store.state.token,
          page: this.page,
          limit: 10,
        };
        circuit(data)
          .then((res) => {
            console.log(res, "列表");
            if (res.data.flag) {
              if (res.data.data.data.length > 0) {
                for (let i = 0; i < res.data.data.data.length; i++) {
                  this.circuit.push(res.data.data.data[i]);
                }
                this.loading = false;
              } else if (res.data.data.data.length == 0) {
                this.finished = true;
              }
            } else {
              this.$toast(res.data.msg);
            }
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },
    toSearchResult() {
      if (!sessionStorage.getItem("Departure")) {
        this.$toast.fail("请选择出发站");
      } else if (!sessionStorage.getItem("arrive")) {
        this.$toast.fail("请选择到达站");
      } else {
        this.$router.push("/searchResult");
      }
    },
    goToIndexAnchorS() {
      this.$router.push({
        path: "/IndexAnchor",
        query: { select: "Departure" },
      });
    },
    goToIndexAnchorE() {
      this.$router.push({ path: "/IndexAnchor", query: { select: "arrive" } });
    },
    exchange() {
      if (this.Departure == "出发站" || this.arrive == "到达站") {
        this.$toast("请选择站点");
      } else {
        this.isExchange = !this.isExchange;
        let exchange = this.Departure;
        this.Departure = this.arrive;
        this.arrive = exchange;
        console.log(this.isExchange);
      }
    },
    week(date) {
      switch (date.getDay()) {
        case 0:
          return "周天";
        case 1:
          return "周一";
        case 2:
          return "周二";
        case 3:
          return "周三";
        case 4:
          return "周四";
        case 5:
          return "周五";
        case 6:
          return "周六";
      }
    },
  },
  filters: {
    dateChange(val) {
      // let index = val.lastIndexOf("\-");
      // return val.substring(0,index)+'月'+val.substring(index+1,val.length)+'日';
      return val;
    },
  },
  beforeMount() {
    // this.isExchange = this.$route.query.isExchange
    this.isDeparture = this.Departure == "出发站" ? true : false;
    this.isArrive = this.arrive == "到达站" ? true : false;
  },

  created() {
    // 储存上级id
    if (this.$route.query.hasOwnProperty('uid')) {
      localStorage.setItem("uid", this.$route.query.uid);
    }
    // 时间选择
    let date;
    if (sessionStorage.getItem("dateSearch")) {
      date = sessionStorage.getItem("dateSearch");
      date = new Date(parseInt(date));
      console.log(date);
    } else {
      date = new Date();
    }
    this.dateSearch =
      date.getMonth() +
      1 +
      "月" +
      date.getDate() +
      "日" +
      " \xa0" +
      this.week(date);
    // 出发到达站选择

    if (sessionStorage.getItem("Departure")) {
      this.Departure = sessionStorage.getItem("Departure").split(",")[2];
    }
    if (sessionStorage.getItem("arrive")) {
      this.arrive = sessionStorage.getItem("arrive").split(",")[2];
    }
    console.log(this.$store.state.token);
    if (this.$store.state.token) {
      this.isToken = true;
      // 分销上级记录接口
      if(localStorage.getItem('uid')){
        this.executeBind();
      }
      let data__ = {
        token: this.$store.state.token,
      };
      banner(data__)
        .then((res) => {
          console.log(res);
          if (res.data.flag) {
            this.banner = res.data.data.banner;
            this.isLoading = false;
          } else {
            this.$toast(res.data.msg);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    } else {
      if (!this.getUrlCode().code) {
        let data_ = {
          type: 1,
        };
        code(data_)
          .then((res) => {
            console.log(res);
            if (res.data.flag) {
              location.href = res.data.data.url
            } else {
              this.$toast(res.data.msg);
            }
          })
          .catch((err) => {
            console.log(err);
          });
      } else {
        let data = {
          code: this.getUrlCode().code,
        };
        this.$axios
          .post(this.$index + this.$api.home.token, this.$Qs.stringify(data))
          .then((res) => {
            console.log(res);
            if (res.data.flag) {
              this.$store.commit("LOGIN", res.data.data.token);
              if (this.$store.state.token) {
                // this.$router.go(0);
                location.href = this.$index + "/home";
              }
            } else {
              this.$toast(res.data.msg);
            }
          })
          .catch((err) => {
            console.log(err);
          });
      }
    }
  },
};
</script>

<style scoped>
/deep/ .van-swipe__indicator--active {
  width: 12px;
  height: 4px;
  border-radius: 100px;
  margin-top: 1px;
  background-color: #0fa1a0;
}

/deep/ .van-swipe__indicator {
  background-color: #0fa1a0;
}

/deep/ .van-swipe__indicators {
  bottom: 52px;
}

.my-swipe .van-swipe-item img {
  z-index: -1;
  width: 100%;
  height: 211px;
}

.searchF {
  width: 100%;
  margin-top: -50px;
}

.search {
  width: 352px;
  height: 178px;
  background-color: #ffffff;
  z-index: 2;
  border-radius: 10px;
  box-shadow: 2px 5px 11px rgba(0, 0, 0, 0.28);
}

.line {
  width: 315px;
  height: 1px;
  background-color: #f1f1f1;
}

.changeBooking {
  width: 315px;
  padding: 16.5px 19px;
  font-size: 17px;
  color: #999999;
}

.Select_active {
  color: #333333;
  width: 50%;
}

/deep/ .van-cell {
  padding: 14px 19px 15px 19px;
}

/deep/ .van-cell:not(:last-child)::after {
  border-bottom: none;
}

.Select_time {
  font-size: 16px;
  color: #333333;
}

.week {
  font-size: 13px;
  color: #666666;
}

.btn {
  width: 301.5px;
  height: 43px;
  padding: 0 26px;
}

/deep/ .van-button {
  line-height: 43px;
}

/deep/ .van-button--normal {
  font-size: 16px;
}

.lineH {
  width: 3.5px;
  height: 14px;
  background-color: #0fa1a0;
}

.titleF {
  width: 351px;
  font-size: 17px;
  color: #333333;
  padding: 26px 12px 20px 12px;
}

.title {
  margin-left: 8px;
  font-size: 14px;
  color: #333333;
}

.listF {
  width: 100%;
}

.list {
  position: relative;
  width: 100%;
  padding: 13px 0;
  background-color: #ffffff;
  border-bottom: 1px #ececec solid;
  font-size: 14px;
  color: #333333;
}

.listFont {
  font-size: 13px;
  color: #666666;
}

.ban {
  position: absolute;
  left: 30%;
}

.abmarL {
  position: absolute;
  left: 55%;
}

.arrow {
  width: 67px;
  height: 1px;
  background-color: #0fa1a0;
}

.rotate {
  margin-left: 62.25px;
  width: 4.75px;
  height: 1px;
  background-color: #0fa1a0;
  -webkit-transform: rotate(-25deg);
  -moz-transform: rotate(-25deg);
}

.mar {
  margin: 4px 0;
}

.marL {
  margin-left: 12px;
}

.marR {
  margin-right: 12px;
}

.money {
  font-size: 16px;
  color: #ff0909;
}

.Remaining {
  font-size: 11px;
  color: #999999;
}

.fontColor {
  color: #888888;
}
.grey {
  color: #888888;
}
</style>